package com.study.test.geneId;


import org.apache.log4j.Logger;

/** 
 * @author Eric Zhang
 * 2013-11-28
 */
public final class Sequences {
	

    private static final Logger LOG = Logger.getLogger(Sequences.class);

	private static UUIDKeyGenerator uuid = new UUIDKeyGenerator();
	private static int num = 1;

    private static int pid = (short)(uuid.getProcessId() & 0xFF);

    private static String pidStr = null;

    private static String mac = null;

    static {
        String str = Integer.toHexString(pid).toUpperCase();
        if(str.length() < 2) {
            str = "0" + str;
        }

        pidStr = str.substring(str.length()-2, str.length());

        mac = uuid.getMachineIDNew(2);
    }
	
	private Sequences(){
	}

    public static synchronized String getPK() {
        StringBuffer buffer = new StringBuffer(16);
        if (num == 9999/*99*/){
            num = 1;
            try {
                LOG.info("-------流水号生成num达到最大值9999，线程等待1秒----------");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                LOG.error("-------流水号生成num达到最大值9999，线程等待异常----------" + e);
            }
        }
        buffer.append(uuid.getCurrentTime(8));
        String str = uuid.intToHexString((num++), 4);
        buffer.append(str);
        buffer.append(mac);
        buffer.append(pidStr);
        String seq = buffer.toString();
        LOG.debug("-----------------sequence（len = " + seq.length() + "）: " + seq);
        return seq;
    }
}